/**
 * All rights Reserved, Designed By 林溪
 * Copyright:    Copyright(C) 2016-2020
 * Company       溪云阁 .
 */

package com.boots.chat.websocket;

import java.io.IOException;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.yeauty.annotation.OnClose;
import org.yeauty.annotation.OnError;
import org.yeauty.annotation.OnMessage;
import org.yeauty.annotation.OnOpen;
import org.yeauty.annotation.ServerEndpoint;
import org.yeauty.pojo.Session;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.boots.chat.business.chat.domain.Chat;
import com.boots.chat.business.chat.service.IChatService;
import com.module.boots.exception.CommonRuntimeException;

import io.netty.handler.codec.http.HttpHeaders;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 单个推送服务
 * @author：溪云阁
 * @date：2020年8月4日
 */
@Slf4j
@ServerEndpoint(path = "/chatSocket", host = "127.0.0.1", port = "8900")
public class ChatSocket {

    @Autowired
    private IChatService chatService;

    /**
     * 新建WebSocket的时候，执行该方法
     * @author 溪云阁
     * @param session
     * @param headers void
     */
    @OnOpen
    @SneakyThrows(CommonRuntimeException.class)
    public void open(Session session, HttpHeaders headers) {
        log.info("WebSocket服务连接成功");
    }

    /**
     * 关闭WebSocket的时候，执行该方法
     * @author 溪云阁
     * @param session void
     */
    @OnClose
    @SneakyThrows(CommonRuntimeException.class)
    public void close(Session session) {
        log.info("WebSocket服务关闭成功");
    }

    /**
     * WebSocket发生异常的时候，执行该方法
     * @author 溪云阁
     * @param session
     * @param th void
     */
    @OnError
    public void error(Session session, Throwable th) {
        log.error("{}", th.fillInStackTrace());
        th.printStackTrace();
    }

    /**
     * WebSocket接收到的消息为字符串的时候，指定该方法
     * @author 溪云阁
     * @param session
     * @param msg void
     */
    @OnMessage
    @SneakyThrows(CommonRuntimeException.class)
    public void message(Session session, String msg) {
        log.info("接收到的信息：{}", msg);
        sendAnswer(session, msg);
    }

    /**
     *
     * @author 溪云阁
     * @param session
     * @param msg void
     */
    private void sendAnswer(Session session, String msg) {
        final QueryWrapper<Chat> query = new QueryWrapper<>();
        query.like("ask", msg);
        final List<Chat> chats = chatService.list(query);
        // 当数据库中有值的时候，随机输出一个值
        if (chats != null && !chats.isEmpty()) {
            final Random random = new Random();
            final int n = random.nextInt(chats.size());
            session.sendText(chats.get(n).getAnswer());
        } else {
            final String url = "http://api.qingyunke.com/api.php?key=free&appid=0&msg=" + msg;
            final OkHttpClient okHttpClient = new OkHttpClient();
            final Request request = new Request.Builder()
                    .url(url)
                    .build();
            final Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {

                @Override
                public void onFailure(Call call, IOException e) {
                    log.error(msg);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final JSONObject json = JSONObject.parseObject(response.body().string());
                    final Chat chat = new Chat();
                    chat.setAsk(msg);
                    chat.setAnswer(json.getString("content"));
                    chatService.saveOrUpdate(chat);
                    session.sendText(json.getString("content"));
                }
            });
        }
    }

}
